<template>
  <el-upload
    v-bind="$attrs"
    action="#"
    class="upload"
    :show-file-list="false"
    :http-request="uploadExcel"
    :before-upload="beforeExcelUpload"
    :on-exceed="handleExceed"
    :on-success="excelUploadSuccess"
    :on-error="excelUploadError"
  >
    <slot>
      <el-button size="small" icon="upload">{{ text }}</el-button>
    </slot>
  </el-upload>
</template>
<script setup>
import { ref } from 'vue'
import { ElNotification, ElMessage } from 'element-plus'
import http from '@/api'

const props = defineProps({
  url: {
    type: String,
    default: ''
  },
  size: {
    type: Number,
    default: 5
  },
  text: {
    type: String,
    default: '导入'
  },
  successTip: {
    type: String,
    default: null
  },
  errorTip: {
    type: String,
    default: null
  },
  params: {
    type: Object,
    default: () => {}
  }
})
const emits = defineEmits(['success'])

const parameter = ref(props)

// 文件上传
const uploadExcel = async param => {
  let excelFormData = new FormData()
  excelFormData.append('file', param.file)
  const { data, code } = await http
    .post(parameter.value.url, excelFormData)
    .catch(() => {})
  if (code === 200) {
    emits('success', data)
  }
}

/**
 * @description 文件上传之前判断
 * @param file 上传的文件
 * */
const beforeExcelUpload = file => {
  const fileSize = file.size / 1024 / 1024 < parameter.value.size

  if (!fileSize)
    setTimeout(() => {
      ElNotification({
        title: '温馨提示',
        message: `上传文件大小不能超过 ${parameter.value.size}MB！`,
        type: 'warning'
      })
    }, 0)
  return fileSize
}

// 文件数超出提示
const handleExceed = () => {
  ElNotification({
    title: '温馨提示',
    message: '最多只能上传一个文件！',
    type: 'warning'
  })
}

// 上传错误提示
const excelUploadError = () => {
  if (parameter.value.errorTip) {
    ElMessage.error(parameter.value.errorTip)
    return
  }
  ElNotification({
    title: '温馨提示',
    message: `批量添加${parameter.value.title}失败，请您重新上传！`,
    type: 'error'
  })
}

// 上传成功提示
const excelUploadSuccess = () => {
  if (parameter.value.successTip) {
    ElMessage.success(parameter.value.successTip)
    return
  }
  ElNotification({
    title: '温馨提示',
    message: `批量添加${parameter.value.title || ''}成功！`,
    type: 'success'
  })
}
</script>
<style lang="scss" scoped></style>
